Introduction $Broadcast(), $Emit() and $On()



$scope and $rootscope support following 3 methods for communication in between widgets.
1.$broadcast()
2.$emit()
3.$on()


The communication in between widgets using above three methods are event driven.

$broadcast() and $emit() allow us to raise an event and
$on is used to capture that event and the event data.

Syntax:

1. $braodcast()
$scope.$broadcast("Event_Name",data);

2. $emit()
$scope.$emit("Event_Name",data);

3. $on()
$scope.$on("Event_Name",function(event,data){

});

Working Process: $broadcast()


 




Working Process: $emit()


 




Example

Parent Widget:

HTML-
 
<div>
<h1>This is a Parent Widget </h1>
 <input type="text" ng-model="c.parentData" />
  <button type="button" ng-click="c.sendDataToChild()">Send Data To Child</button>
 
  <h2>Getting Data from Child</h2>
  <div>{{c.data.child2data}}</div>
<br>
  <br>
  <widget id="b_child_one"></widget>
  <br>
  <br>
  <widget id="b_child_two"></widget>
</div>

Client Code-

api.controller=function($rootScope,$scope) {
  /* widget controller */
  var c = this;
    $scope.$on("child_event",function(event,data){
c.data.child2data=data;
});
    c.sendDataToChild =function(){
        var sData=c.parentData;
        $scope.$broadcast("parent_event",sData);    
    }
    
};

Child 1 Widget:

HTML-

<div>
<h1>This is Child One widget</h1>
  <div> Get Parent Data : {{c.data.ChildgetData1}}</div>
  <div>Get Child 2 Data: {{c.data.child2data1}}</div>
</div>

Client Code-

api.controller=function($rootScope,$scope) {
  /* widget controller */
  var c = this;
        $scope.$on("parent_event",function(event,data){
c.data.ChildgetData1=data;
});
        $scope.$on("child_event",function(event,data){
c.data.child2data1=data;
});    
        $rootScope.$on("child_event",function(event,data){
c.data.child2data1=data;
});
    
};

Child 2 Widget:

HTML-

<div>
<h1>This is Child Two widget</h1>
 <div> Get Parent Data:  {{c.data.ChildgetData}}</div>
  <br>
  <h2>Sending data to Parent and other widget using broadcast</h2>
<input type="text" ng-model="c.child2Data" />
  <button type="button" ng-click="c.sendDataToOthers()">Send Data To Others</button>
</div>

Client Code-

api.controller=function($rootScope,$scope) {
  /* widget controller */
  var c = this;
    $scope.$on("parent_event",function(event,data){
c.data.ChildgetData=data;
});
    c.sendDataToOthers=function(){        
        var sData=c.child2Data;
        $rootScope.$broadcast("child_event",sData);
    
    }    
};